package db;

import model.Uselogin;

import java.sql.*;
import java.util.ArrayList;

public class Database {
    static Connection conn = null;


    public  Database() throws ClassNotFoundException, SQLException {

        Class.forName("com.mysql.cj.jdbc.Driver");//注册驱动
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/login?serverTimezone=GMT%2B8", "root", "1234");
    }
    public void showConnection() {
        if (conn == null) {
            System.out.println("数据库连接失败");
        } else {
//            System.out.println(conn);
            System.out.println("数据库连接成功");
        }
    }

    //关闭链接
    public void close() throws SQLException {
        conn.close();
    }

    //login表里面添加数据
    public void insert(String username, String password) throws SQLException {
        //PreparedStatement，是java.sql包中的接口，继承了Statement，并与之在两方面有所不同，包含已编译的 SQL 语句.
        PreparedStatement prep = conn.prepareStatement("insert into login.login value (null,?,?)");//id,username,password
        prep.setString(1, username);
        prep.setString(2, password);
        prep.execute();//执行操作
    }
    //查询账号是否存在

    //查询总表
    public ArrayList<Uselogin> getAllUsers() throws SQLException {
        ArrayList<Uselogin> uselist = new ArrayList<Uselogin>();
        PreparedStatement prep = conn.prepareStatement("select * from login.login");
        prep.execute();
        ResultSet rs = prep.executeQuery();
        while (rs.next()) {
            int myid = rs.getInt("id");
            String myname = rs.getString("username");
            String mypwd = rs.getString("password");
            uselist.add(new Uselogin(myid,myname,mypwd));
        }
        return uselist;
    }
    //在表里查询数据
    public static Uselogin getUser(String username) throws SQLException {
        PreparedStatement prep = conn.prepareStatement("select * from login.login where username = ?");
        prep.setString(1, username);
        prep.execute();
        //get方法获取对应的类型的数据，当然需要结合while
        ResultSet rs = prep.getResultSet();
        if (rs.next()) {
            int myid = rs.getInt("id");
            String myname = rs.getString("username");
            String mypwd = rs.getString("password");
            return new Uselogin(myid, myname, mypwd);
        }
        return null;
    }

    public static Uselogin login(String username, String password) throws SQLException {
        PreparedStatement prep = conn.prepareStatement("select password from login.login where username=?");
        prep.setString(1,username);
        prep.execute();
        ResultSet rs = prep.getResultSet();
        if (rs.next()) {
            String mypwd = rs.getString("password");
            if (password.equals(mypwd)) {
                return getUser(username);
            } else
                return null;
        }
        else
            return null;

    }
}
